#2021/11/17
#10:29
import requests
import asyncio
import aiohttp
import aiofiles
import json
#https://dushu.baidu.com/pc/detail?gid=4306063500   西游记地址
#https://dushu.baidu.com/api/pc/getCatalog?data={%22book_id%22:%224306063500%22}
#https://dushu.baidu.com/api/pc/getChapterContent?dataa={"book_id":"4306063500","cid":"4306063500|11348571","need_bookinfo":1}


async def download(book_id, cid , title):
    path ="C:\\Users\\指鹿\\PycharmProjects\\reptile\\Thread\\resource"+title+".txt"
    data={
        "book_id":book_id,
        "cid":f"{book_id}|{cid}" ,
        "need_bookinfo":1
    }
    data = json.dumps(data)
    url =f"https://dushu.baidu.com/api/pc/getChapterContent?data={data}"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            dic = await resp.json()
            #await asyncio.sleep(1)
            async with aiofiles.open(path,mode="w",encoding="utf-8") as f:
                await f.write(dic['data']['novel']['content'])


def getCatalog(url,book_id):
    response = requests.get(url)
    Catalog = response.json()
    tasks = []
    for item in Catalog['data']['novel']['items']:
        cid = item['cid']
        title = item['title']
        tasks.append(download(book_id,cid,title))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))

if __name__ == '__main__':
    book_id = "4316436997"
    url = 'https://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"' + book_id + '"}'
    getCatalog(url,book_id)


